package com.example.module_home.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewpager.widget.PagerAdapter
import com.example.lib_common.user.UserUtils
import com.example.lib_mvicore.ui.BaseMVIFragment
import com.example.libraryaccount.intent.AccountIntent
import com.example.libraryaccount.state.AccountState
import com.example.module_home.R
import com.example.module_home.databinding.FragmentHomeBinding
import com.example.module_home.intent.SimpleTypeIntent
import com.example.module_home.state.SimpleTypeState
import com.example.module_home.viewmodel.SimpleTypeViewModel
import com.example.viewmodel.AccountViewModel
import com.ivideo.home.model.entity.SimpleTypeEntity
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


class HomeFragment : BaseMVIFragment() {
    lateinit var mBinding: FragmentHomeBinding
    private lateinit var mSimpleTypeViewModel: SimpleTypeViewModel
    private lateinit var mAccountViewModel: AccountViewModel
    override fun generateViewModel() {
        mSimpleTypeViewModel = ViewModelProvider(requireActivity())[SimpleTypeViewModel::class.java]
        mAccountViewModel = ViewModelProvider(requireActivity())[AccountViewModel::class.java]
    }

    /**
     * view
     */
    override fun initView() {
        super.initView()
        initTitleBar()
        initRedPacketView()
    }

    private fun initTitleBar(){
        val list: MutableList<String> = mutableListOf()
        list.add("视频资讯1")
        list.add("视频资讯2")
        list.add("视频资讯3")
        mBinding.xgtbHomeTitlebar.setTextList(list.toList())
    }
    private fun initRedPacketView() {
        //设置红包进度执行结束金额
        mBinding.rpvHomeRedpacket.setTvNum(100);
    }

    /**
     * 事件
     */
    override fun initEvent() {
        mBinding.xgtbHomeTitlebar.setTitleBarClickCallback {
            showMsg("点击了标题栏 $it")
        }
        /**
         * 上报用户金币额
         */
        mBinding.rpvHomeRedpacket.setStateCallback {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED){
                    if(UserUtils.isLogin()){
                        mAccountViewModel.intents.send(AccountIntent.ModifyCoinAmount(UserUtils.getCurrentUser()!!.accountid,100))
                    }else{
                        showMsg("登陆后获取金币奖励")
                    }
                }
            }
        }
    }

    /**
     * 数据
     */
    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mSimpleTypeViewModel.intents.send(SimpleTypeIntent.getSimpleType)
            }
        }
    }




    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentHomeBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    /**
     * 处理网络请求结果
     */
    override fun handleState() {
       lifecycleScope.launch {
           repeatOnLifecycle(Lifecycle.State.STARTED){
               mSimpleTypeViewModel.simpleTypeFlow_.collect{
                   when(it){
                       is SimpleTypeState.Failed->{
                           showMsg("网络请求失败 ${it.msg}")
                       }
                       is SimpleTypeState.Init->{
                           showMsg("初始化")
                       }
                       is SimpleTypeState.SimpleTypeSuccess->{
                           generateTabs(it.list)
                       }
                       is SimpleTypeState.Empty->{
                           showMsg("空数据")
                       }

                   }
               }
           }
       }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mAccountViewModel.state.collect{
                    when (it) {
                        is AccountState.ModifyCoinAmountSuccessState -> {
                            showMsg("上报成功")
                        }
                        is AccountState.ModifyCoinAmountFailedState -> {
                            showMsg("上报失败")
                        }
                        else -> {

                        }
                    }
                }
            }
        }
    }

    /**
     * 展示tabs数据：动态生成fragment
     */
    private fun generateTabs(list: List<SimpleTypeEntity>?) {
        val adapter= list?.let { HomePagerAdapter(it,this.childFragmentManager) }
        mBinding.vpHome.adapter=adapter
        mBinding.tlHomeVideotype.setupWithViewPager(mBinding.vpHome)
        mBinding.vpHome.adapter?.notifyDataSetChanged()

    }

    /**
     * Home页面ViewPager适配器
     */
    class HomePagerAdapter(val types:List<SimpleTypeEntity>,val manager: FragmentManager): FragmentStatePagerAdapter(manager) {
        private val fragments:MutableList<Fragment>
        init {
            fragments= mutableListOf()
            for (entity in types){
                val fragment=SimpleTypeFragment()
                val bundle=Bundle()
                bundle.putString("channelid",entity.channelid)
                fragment.arguments=bundle
                fragments.add(fragment)
            }
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return types.get(position).typename
        }

        override fun getCount(): Int {
            return fragments.size
        }

        override fun getItem(position: Int): Fragment {
            return fragments.get(position)
        }

        override fun getItemPosition(`object`: Any): Int {
            return PagerAdapter.POSITION_NONE
        }
    }

}